package com.xiaoyu.net;

import in.srain.cube.concurrent.SimpleTask;
import in.srain.cube.request.IRequest;
import in.srain.cube.request.IRequestProxy;
import okhttp3.Request;

/**
 * Created by srain on 9/5/17.
 */
public class DoRequestTask<T, OriginDataType> extends SimpleTask {

    private T mData;
    private IRequest<T, OriginDataType> mCubeRequest;
    private Request mRequest;
    private IRequestProxy<OriginDataType> mRequestProxy;

    public DoRequestTask(IRequest<T, OriginDataType> cubeRequest, Request request, IRequestProxy<OriginDataType> requestProxy) {
        mCubeRequest = cubeRequest;
        mRequest = request;
        mRequestProxy = requestProxy;
    }

    @Override
    public void doInBackground() {
        try {
            mData = RequestProvider.doSyncRequest(mCubeRequest, mRequest, mRequestProxy);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    @Override
    public void onFinish(boolean canceled) {
        if (mData == null || mCubeRequest.getFailData() != null) {
            mCubeRequest.onRequestFail(null, mCubeRequest.getFailData());
        } else {
            mCubeRequest.onRequestSuccess(mData);
        }
    }
}
